package com.itheima.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class BeanFactory {
    /*
    * 1.加载bean.properties配置文件
    * 2.读取配置文件内容,根据key获取value
    * 3.根据得到的value即全类名反射创建对象
    * 4.存储对象到map集合中
    * */
    public static final Map<String,Object> cache = new HashMap<>();
    //对象只创建一次,所以写在静态代码块中
    static{
        Properties properties = new Properties();
        InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //遍历keys得到所有的key
        Set<String> keys = properties.stringPropertyNames();
        keys.forEach(key->{
            //根据key获取value 全类名
            String className = properties.getProperty(key);
            //全类名反射创建对象
            Object bean = null;
            try {
                bean = Class.forName(className).newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //key=bean的对应关系存储到map集合中
            cache.put(key,bean);
        });
    }

    public static<T> T getBean(String name,Class<T> tClass){
        return (T) cache.get(name);
    }
}
